﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Diary.Win
{
    public class Global
    {
        static Global _DefaultInstance = null;
        public static Global Default
        {
            get
            {
                if (_DefaultInstance == null)
                {
                    _DefaultInstance = new Global();
                }
                return _DefaultInstance;
            }
        }

        public bool Init()
        {
            DBFilepath = string.Format("{0}{1}", Application.StartupPath, DBFilename);
            return true;
        }

        public string DBFilename = "Diray.db";
        public string DBFilepath = "";

        public bool BackupDB()
        {
            string backup_filepath = string.Format("{0}\\{1}", BAL.Setting.get_string_value("BackupPath"), System.DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
            System.IO.File.Copy(Global.Default.DBFilepath, backup_filepath, true);
            BAL.DBController dbTest = new BAL.DBController();
            if (!dbTest.connectToDatabase(backup_filepath)) return false;
            dbTest.disconnect();
            return true;
        }

        public void RestoreDB()
        {
            if (MessageBox.Show("确定要从备份目录恢复数据吗？", "", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = BAL.Setting.get_string_value("BackupPath");
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                BAL.DBController dBTest = new BAL.DBController();
                if (dBTest.connectToDatabase(Global.Default.DBFilepath))
                {
                    System.IO.File.Copy(fileDialog.FileName, Global.Default.DBFilepath, true);
                    MessageBox.Show("数据已成功恢复，现在将重启应用程序");
                    Application.Restart();
                }
            }
        }
    }
}
